package com.karaku.karaku_collector.util;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.BatteryManager;

import com.google.gson.annotations.SerializedName;
import com.karaku.karaku_collector.App;

/**
 * Created by guopi on 2017/10/27 0027.
 */

public class MyBatteryManager {

    private static final int STATE_NOT_CHARGE = 1;
    private static final int STATE_CHARGING = 2;
    private static final int STATE_CHARGING_FULL = 3;

    private static MyBatteryManager instance;

    public static MyBatteryManager getInstance() {
        if (instance == null) {
            instance = new MyBatteryManager();
        }
        return instance;
    }

    private MyBatteryManager.BatteryStat stat = new MyBatteryManager.BatteryStat();

    private BroadcastReceiver batteryReceiver = new BroadcastReceiver() {
        public void onReceive(Context context, Intent intent) {
            updateBatteryState(intent);
        }
    };

    private MyBatteryManager() {
        IntentFilter filter = new IntentFilter(Intent.ACTION_BATTERY_CHANGED);
        Intent intent = App.getInstance().registerReceiver(batteryReceiver, filter);
        updateBatteryState(intent);
    }

    public MyBatteryManager.BatteryStat getStat() {
        return stat;
    }

    private void updateBatteryState(Intent intent) {
        int status = intent.getIntExtra(BatteryManager.EXTRA_STATUS, -1);
        if (status == BatteryManager.BATTERY_STATUS_CHARGING) {
            stat.isInCharge = STATE_CHARGING;
        } else if (status == BatteryManager.BATTERY_STATUS_FULL) {
            stat.isInCharge = STATE_CHARGING_FULL;
        } else {
            stat.isInCharge = STATE_NOT_CHARGE;
        }
        int current = intent.getExtras().getInt("level");// 获得当前电量
        float total = intent.getExtras().getInt("scale");// 获得总电量
        stat.batteryLevel = current / total;

        LogUtil.d("BATTERY", "chargeState:" + stat.isInCharge +" percent:" + stat.batteryLevel);
    }

    public static class BatteryStat {
        @SerializedName("isInCharge")
        public int isInCharge = STATE_NOT_CHARGE;
        @SerializedName("batteryLevel")
        public float batteryLevel;
    }
}
